const log4js = require('koa-log4');
const logger = log4js.getLogger('qiniu::uploader');
const nconf = require('nconf');
const qiniu = require('qiniu');
const qiniu_config = nconf.get('qiniu');
const bucket = qiniu_config['bucket_name'];
const accessKey = qiniu_config['access_key'];
const secretKey = qiniu_config['secret_key'];
const domain = qiniu_config['domain'];
const zone = qiniu_config['zone'];
const config = new qiniu.conf.Config();
config.zone = qiniu.zone[zone];

// 鉴权对象mac
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

const formUploader = new qiniu.form_up.FormUploader(config);
const putExtra = new qiniu.form_up.PutExtra();

//自定义凭证有效期（默认1小时，expires单位为秒，为上传凭证的有效时间）
const options = {
	scope: bucket,
	expires: 10 * 60 //10分钟
};

const putPolicy = new qiniu.rs.PutPolicy(options);

/**
 * 数据流上传（表单方式）
 * @param key
 * @param file_stream
 * @returns {Promise}
 */
const uploadByStream = async (key, file_stream) => {
	const uploadToken = putPolicy.uploadToken(mac);
	return new Promise((resolve, reject) => {
		formUploader.putStream(uploadToken, key, file_stream, putExtra, (respErr, respBody, respInfo) => {
			if (respErr) {
				throw respErr;
			}
			if (respInfo.statusCode == 200) {
				respBody.token = uploadToken;
				respBody.path = domain + key;
				logger.info(respBody);
				resolve(respBody);
			} else {
				logger.error(respInfo.statusCode);
				logger.error(respBody);
				reject(respBody)
			}
		});
	});
};

exports = module.exports = {
	uploadByStream
};